﻿using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using ZilLion.Core.Unities.UnitiesMethods;
using ZilLion.Service.Core.ConfigManager.Manager;
using ZilLion.Service.Core.Domain.EntityBase;
using ZilLion.Service.Core.Infrastructure;
using ZilLion.Service.Core.Infrastructure.Base;
using ZilLion.Service.Core.Ioc;

namespace ZilLion.Service.Core.Starter.Controllers
{
    /// <summary>
    ///     用于发放ZLJWT
    /// </summary>
    [Route("Api/Jwt")]
    public class JwtDistributeController : ZilLionControllerBase
    {
        private Dictionary<string, dynamic> InterceptJwtpayload(Dictionary<string, string> formpayload, string apptype)
        {
            if (!IocConfig.ComponentLoaderCache.ContainsKey(apptype.ToLower())) return null;
            var realpayload = IocConfig.ComponentLoaderCache[apptype.ToLower()].InterceptJwtpayload(formpayload);
            if (realpayload == null) return null;
            var payload = new Dictionary<string, dynamic>();
            foreach (var info in realpayload)
                if (payload.ContainsKey(info.Key))
                    payload[info.Key] = info.Value;
                else
                    payload.Add(info.Key, info.Value);

            return payload;
        }

        /// <summary>
        ///     创建jwt
        /// </summary>
        [Route("GetJwt/{apptype}")]
        [HttpPost]
        [AllowAnonymous]
        public TokenResponse CreateToken([FromBody] Dictionary<string, string> formpayload, string apptype)
        {
            #region 拦截(反射动态调用)

            var realpayload = InterceptJwtpayload(formpayload, apptype);

            #endregion

            if (realpayload == null)
                return new TokenResponse
                {
                    Errormodel =
                        new WebErrorModel
                        {
                            ErrMessage = "formpayload数据不合法!",
                            ErrDetail = JsonConvert.SerializeObject(formpayload)
                        }
                };

            #region 生成Token

            if (!realpayload.ContainsKey("exp"))
            {
                var exp =
                    Math.Round(
                        (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc))
                        .TotalSeconds +
                        60 * 60 * 24).ToInt64OrDefault(0); //一天过期
                realpayload.Add("exp", exp); //过期时间（秒）);
            }

            var token = JwtTokenUtility.EncodeJwtToken(realpayload,
                ZilLionConfigurationManager.GetConfigInstance<WebApiAppConfig>().JwtSecretKey);

            return new TokenResponse
            {
                CreatedTime = DateTime.Now.GetNowChinaTime(),
                NextExpTime =
                    new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).GetNowChinaTime()
                        .AddSeconds(realpayload["exp"]),
                Token = token
            };

            #endregion
        }
    }

    public class TokenResponse : ResponseBase
    {
        public DateTime CreatedTime { get; set; }

        public string Token { get; set; }

        public DateTime NextExpTime { get; set; }
    }
}